<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="订单编码" prop="orderId">
                <el-input
                        v-model="queryParams.orderId"
                        placeholder="请输入订单编码"
                        clearable
                        @keyup.enter="handleQuery"
                />
            </el-form-item>
            <!--<el-form-item label="物流公司" prop="logisticsCompany">-->
                <!--<el-input-->
                        <!--v-model="queryParams.logisticsCompany"-->
                        <!--placeholder="请输入物流公司"-->
                        <!--clearable-->
                        <!--@keyup.enter="handleQuery"-->
                <!--/>-->
            <!--</el-form-item>-->
            <el-form-item label="物流单号" prop="logisticsNumber">
                <el-input
                        v-model="queryParams.logisticsNumber"
                        placeholder="请输入物流单号"
                        clearable
                        @keyup.enter="handleQuery"
                />
            </el-form-item>
            <!--<el-form-item label="运输方式" prop="transportMode">-->
                <!--<el-input-->
                        <!--v-model="queryParams.transportMode"-->
                        <!--placeholder="请输入运输方式"-->
                        <!--clearable-->
                        <!--@keyup.enter="handleQuery"-->
                <!--/>-->
            <!--</el-form-item>-->
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>


      <el-card>
        <template #header>
          <Bell style="width: 1em; height: 1em; vertical-align: middle;" />
          <span style="vertical-align: middle; margin-left: 5px">订单状态</span>
        </template>
        <div style="margin-top: 20px" v-if="order.orderStatus">
          <el-steps :active="formatStepStatus(order.orderStatus)" finish-status="success" align-center>
            <el-step
                v-for="(step, index) in steps"
                :key="index"
                :title="step.title"
                :description="getDescription(index)"
            ></el-step>
          </el-steps>
        </div>
        <div style="margin-top: 20px" v-else>
          <div style="text-align: center; color: #909399; margin-top: 20px;">暂无数据</div>
        </div>
      </el-card>


    </div>

    <div class="card-container">

      <el-card class="card-item" style="height:535px">
        <template #header>
          <Message style="width: 1em; height: 1em; vertical-align: middle;" />
          <span style="vertical-align: middle; margin-left: 5px">物流信息</span>
        </template>
        <div class="timeline-container" v-if="timelineEvents.length > 0">
          <el-timeline>
            <el-timeline-item
                v-for="(event, index) in timelineEvents"
                :key="index"
                :timestamp="event.time"
                placement="top"
            >
              {{ event.desc }}
            </el-timeline-item>
          </el-timeline>
        </div>
        <div class="timeline-container" v-else>
          <div style="text-align: center; color: #909399; margin-top: 25%;">暂无数据</div>
        </div>
      </el-card>


        <el-card class="card-item" style="height:535px ;flex-grow: 1; margin-left:40px; margin-right: 40px;">
          <template #header>
            <Guide style="width: 1em; height: 1em; vertical-align: middle;" />
            <span style="vertical-align: middle; margin-left: 5px">物流追踪</span>
          </template>
          <div v-if="timelineEvents.length > 0">
            <MapContainer :logistic-info="logisticsEvents" :current="current" />
          </div>
          <div class="timeline-container" v-else>
            <div style="text-align: center; color: #909399; margin-top: 25%;">暂无数据</div>
          </div>
        </el-card>


    </div>




</template>

<script setup name="Trace">
    import  { listTrace, getTrace, delTrace, addTrace, updateTrace } from "@/api/system/trace.js";
    import { listOrder, getOrder, delOrder, addOrder, updateOrder } from "@/api/system/order.js";
    import {getDelivery} from "@/api/system/history.js";
    import {getCurrentDelivery} from "@/api/system/delivery.js";
    import {getLogistics, getLogisticsHistory , getDeliveryIdByTrackingNo} from "@/api/delivery/delivery.js";
    import {getDetailsByOrderNumber} from "@/api/delivery/transport.js";
    import MapContainer from "@/components/GaoDeMap/MapContainer.vue";
    import errorCode from "../../utils/errorCode.js";
    import {Guide, Message} from "@element-plus/icons-vue";
    import {getCustomerAddr} from "@/api/system/addr.js";

    const { proxy } = getCurrentInstance();

    const traceList = ref([]);
    const historyList = ref([]);
    const open = ref(false);
    const loading = ref(true);
    const showSearch = ref(true);
    const ids = ref([]);
    const single = ref(true);
    const multiple = ref(true);
    const total = ref(0);
    const title = ref("");
    const order = ref({}); // 修改这里
    const orderTrace = ref([]);
    const current = ref([])
    const trackPoints = ref([]);
    const customerAddr =  ref();


    const steps = ref([
        { title: "待确认" },
        { title: "待支付" },
        { title: "已支付" },
        { title: "待发货" },
        { title: "已发货" },
        { title: "运输中" },
        { title: "派送中" },
        { title: "待签收" },
        { title: "已签收" }
    ]);

    const timelineEvents = ref([]);

    const logisticsEvents = ref([
      {
        location: '辽宁省沈阳市',
        remarks: '订单完成，客户签收',
        timeStamp: '2025-01-05 16:11:22',
        longitude: 123.447906,
        latitude: 41.66857
      },
      {
        location: '河南省许昌市',
        remarks: '返回市区，准备送达',
        timeStamp: '2025-01-04 16:11:22',
        longitude: 113.871787,
        latitude: 34.043586
      },
      {
        location: '湖南省常德市',
        remarks: '开始配送（出库）',
        timeStamp: '2025-01-02 16:11:22',
        longitude: 111.72373,
        latitude: 29.011584
      },
    ])


    const data = reactive({
        form: {},

        queryParams: {
            pageNum: 1,
            pageSize: 10,
            orderId:null,
            customerId: null,
            shippingAddress: null,
            estimatedShippingDate: null,
            actualShippingDate: null,
            logisticsCompany: null,
            logisticsNumber: null,
            transportMode: null,
            transferStation: null,
            arrivalTimeAtTransfer: null,
            finalDestination: null,
            estimatedArrivalTime: null,
            actualArrivalTime: null,
            note: null
        },

    });

    const { queryParams, form, rules } = toRefs(data);

    async function queryExpressDelivery(num, phone = null) {

      console.log('查询快递信息')

      const url = "https://api.huiniao.top/interface/third/kuaidi";

      // 构建请求体参数
      const formData = new FormData();
      formData.append("num", num); // 快递单号，必填项

      if (phone) {
        formData.append("phone", phone); // 收件人电话，非必填项
      }

      try {
        const response = await fetch(url, {
          method: 'POST',
          body: formData,
          headers: {
            // 如果有认证或其他头部信息需要添加，可以在headers里指定
          }
        });

        console.log('成功发送请求')
        console.log('response:', response)

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();

        console.log('成功接收返回数值')
        console.log('data:', data)

        // 检查响应码是否为1，表示成功
        if (data.code === 1) {
          console.log('查询成功:', data);
          return data;
        } else {
          console.error('查询失败:', data.info);
          throw new Error(data.info || '查询失败');
        }
      } catch (error) {
        console.error('请求失败:', error.message);
        throw error;
      }
    }


    function convertTimestampToISO(timestamp) {

      const date = new Date(timestamp*1000);
      return date.toLocaleString()
    }


    /** 查询订单状态跟踪列表 */
    function getList() {
        loading.value = true;
        console.log("queryParams:", queryParams.value)
        getOrderByOrderId(queryParams.value.orderId)
        getDetailsByOrderNumber(queryParams.value.orderId).then(response => {
          console.log("orderNum response:", response);
          const trackingNo = response[0].trackingNumber;
          console.log("trackingNo:", trackingNo)
          getDeliveryIdByTrackingNo(trackingNo).then(response => {
            console.log("deliveryId:",response)
            const deliveryId = response
            getHistoryByDeliveryId(deliveryId)
          });
        });
        // listTrace(queryParams.value).then(response => {
        //     traceList.value = response.rows;
        //     orderTrace.value = response.rows;
        //     total.value = response.total;
        //     loading.value = false;
        //  getHistory();
        //  getOrderByOrderId(response.rows[0].orderId)
        // });
    }

    function formatDeliveryMessage(value) {

      console.log('value:', `${value.location}  ${value.remarks}`)
      return `${value.location}  ${value.remarks}`;


    }

    function convertToLogisticInfo(apiData) {
      return apiData.map(item => ({
        location: item.location,
        remarks: item.remarks,
        timeStamp: item.timeStamp,
        longitude: parseFloat(item.longitude),
        latitude: parseFloat(item.latitude)
      }));
    }

    async function geocodeAddress(address) {
      try {
        const response = await fetch(`https://restapi.amap.com/v3/geocode/geo?address=${encodeURIComponent(address)}&key=48dff654e078158ff016c701f2755ddf`);
        const data = await response.json();
        if (data.status === '1' && data.geocodes.length > 0) {
          const location = data.geocodes[0].location.split(',');
          return { longitude: parseFloat(location[0]), latitude: parseFloat(location[1]) };
        } else {
          console.error('Geocoding failed:', data.info);
          return null;
        }
      } catch (error) {
        console.error('Geocoding request failed:', error.message);
        return null;
      }
    }

    async function getHistory() {
      getLogisticsHistory(orderTrace.value[0].logisticsNumber).then(response => {
        historyList.value = response;
        getLogistics(orderTrace.value[0].logisticsNumber).then(async response => {
          current.value = response;
          logisticsEvents.value = convertToLogisticInfo(historyList.value);

          // 处理 current 数据
          if (current.value.longitude === null || current.value.latitude === null) {
            const geocodeResult = await geocodeAddress(current.value.location);
            if (geocodeResult) {
              current.value.longitude = geocodeResult.longitude;
              current.value.latitude = geocodeResult.latitude;
            }
          }

          logisticsEvents.value.push(current.value);
          historyList.value.push(current.value);
          historyList.value.sort((a, b) => new Date(b.timeStamp) - new Date(a.timeStamp));

          timelineEvents.value = [];
          historyList.value.forEach(item => {
            const message = formatDeliveryMessage(item);
            const time = new Date(item.timeStamp);
            if (isNaN(time.getTime())) {
              console.error('Invalid date found:', item.timeStamp);
              timelineEvents.value.push({ time: 'Invalid Date', desc: message });
            } else {
              timelineEvents.value.push({ time: time.toLocaleString(), desc: message });
            }
          });

          console.log('timelineEvents:', timelineEvents.value);
          console.log('logisticsEvents:', logisticsEvents.value);
        });
      });
    }

    async function getHistoryByDeliveryId(deliveryId) {
      getLogisticsHistory(deliveryId).then(response => {
        historyList.value = response;
        getLogistics(deliveryId).then(async response => {
          current.value = response;
          logisticsEvents.value = convertToLogisticInfo(historyList.value);

          // 处理 current 数据
          if (current.value.longitude === null || current.value.latitude === null) {
            const geocodeResult = await geocodeAddress(current.value.location);
            if (geocodeResult) {
              current.value.longitude = geocodeResult.longitude;
              current.value.latitude = geocodeResult.latitude;
            }
          }

          logisticsEvents.value.push(current.value);
          historyList.value.push(current.value);
          historyList.value.sort((a, b) => new Date(b.timeStamp) - new Date(a.timeStamp));

          timelineEvents.value = [];
          historyList.value.forEach(item => {
            const message = formatDeliveryMessage(item);
            const time = new Date(item.timeStamp);
            if (isNaN(time.getTime())) {
              console.error('Invalid date found:', item.timeStamp);
              timelineEvents.value.push({ time: 'Invalid Date', desc: message });
            } else {
              timelineEvents.value.push({ time: time.toLocaleString(), desc: message });
            }
          });

          console.log('timelineEvents:', timelineEvents.value);
          console.log('logisticsEvents:', logisticsEvents.value);
        });
      });
    }

    function getCurrent(){

      getDetailsByOrderNumber('O50001').then(response =>{
        console.log('Transport',response)
})
    }

    function getDeliveryId(){
      getDeliveryIdByTrackingNo('T001').then(response =>{
        console.log('DeliveryId',response)
      })
    }

    // 取消按钮
    function cancel() {
        open.value = false;
        reset();
    }

    // 表单重置
    function reset() {
        form.value = {
            orderId: null,
            customerId: null,
            shippingAddress: null,
            estimatedShippingDate: null,
            actualShippingDate: null,
            logisticsCompany: null,
            logisticsNumber: null,
            transportMode: null,
            transferStation: null,
            arrivalTimeAtTransfer: null,
            finalDestination: null,
            estimatedArrivalTime: null,
            actualArrivalTime: null,
            note: null
        };
        proxy.resetForm("traceRef");
    }

    function getOrderByOrderId(orderId){

        getOrder(orderId).then(response =>{
            order.value = response.data;
            getCustomerAddr(order.value.customerId,order.value.addressId).then(response =>{
                customerAddr.value = response.data;
                console.log('customerAddr',customerAddr.value)
            })

        })
    }

    function  getDescription(index) {
        const activeIndex = this.formatStepStatus(this.order.orderStatus);

        return index <= activeIndex ? this.order.modifiedDate: '';
    }

   function formatStepStatus(value) {

        return parseInt(value)-1;
    }


    /** 搜索按钮操作 */
    function handleQuery() {
      if (!queryParams.value.orderId && !queryParams.value.logisticsNumber) {
        proxy.$message.warning('请输入订单编码或物流单号');
        return;
      }

      if(queryParams.value.orderId){
        queryParams.value.pageNum = 1;
        getList();
      }else if(queryParams.value.logisticsNumber){
        queryParams.value.pageNum = 1;
        getOrderByOrderId(1);
        getHistoryByDeliveryId(queryParams.value.logisticsNumber);
      }

    }

    /** 重置按钮操作 */
    function resetQuery() {
        proxy.resetForm("queryRef");
        order.value = {};
        timelineEvents.value = [];
    }

    function getOrderTrace(){
      getTrace(order.value.orderId).then(response => {
        traceList.value = response.data;
        orderTrace.value = response.data;
      })
    }


    // queryExpressDelivery('777273011816770','15842640138')
    //     .then(response => {
    //       // 处理成功的响应数据
    //       console.log('快递信息:', response.data);
    //       timelineEvents.value = response.data.list.reverse();
    //       timelineEvents.value.forEach(item => {
    //         item.time = convertTimestampToISO(item.time);
    //       })
    //       console.log('timelineEvents:', timelineEvents.value)
    //     })
    //     .catch(error => {
    //       // 处理错误
    //       console.error('发生错误:', error);
    //     });
</script>

<style scoped>
.card-container {
  display: flex;
  width: 100%;
  height: 100%; /* 根据需要调整 */
  margin-right: 20px;
  margin-left: 20px;
}

.card-item {
  width: 100%;
  height: 100%;
}

.timeline-container {
  height: 480px; /* 设置固定高度 */
  overflow-y: auto; /* 启用垂直滚动 */
  padding-right: 10px; /* 可选：为滚动条留出空间 */
}
</style>
